<?php
declare (strict_types = 1);

namespace app\controller\backend;

use app\model\Attachment;
use app\model\SysSetting;
use app\service\upload\Upload;
use app\validate\AttachmentValidate;
use think\exception\ValidateException;

class AttachmentController extends BaseController
{
    protected  $type = [
        'file'    => 4,
        'image'    => 2,
        'video'    => 3,
        'mp3'    => 5,
        'zip'   => 1,
    ];

    /**
     * 显示资源列表
     *
     * @return \think\response\Json
     * @throws \app\exception\ModelException
     */
    public function index(Attachment $attachment): \think\response\Json
    {
        $type = (int)input('type');
        $where = [
            'seller_id' => $this->admin['seller_id'],
            'is_del' => 1,
        ];
        if($type){
            $where['type'] = $type;
        }
        $limit = 10;
        $limitParam = (int)input('limit');
        if($limitParam){
            $limit = $limitParam;
        }
        $attachmentList = $attachment->getAttachmentList($where,$limit);
        return json(pageReturn($attachmentList));
    }

    /**
     * 保存新建的资源
     *
     * @return \think\response\Json
     * @throws \app\exception\ModelException
     * @throws \app\exception\ModelEmptyException
     */
    public function save(Attachment $attachment): \think\response\Json
    {
        if(request()->isPost()){
            $param = input('post.');
            foreach($param as &$val){
                try{
                    validate(AttachmentValidate::class)->scene('save')->check($val);
                    $val['seller_id'] = $this->admin['seller_id'];
                }catch (ValidateException $e){
                    return jsonReturn(-1, $e->getError());
                }
            }
            $res = $attachment->addAllCustomData($param);
            return json($res);
        }
        return jsonReturn(-3,'请求方法错误');
    }

    /**
     * 显示指定的资源
     *
     * @return \think\response\Json
     * @throws \app\exception\ModelException
     * @throws \app\exception\ModelEmptyException
     */
    public function read(Attachment $attachment): \think\response\Json
    {

        $id = (int)input('id');
        if(!$id){
            return jsonReturn(-1,'附件ID不能为空');
        }
        $where = [
            'id' => $id,
            'seller_id' => $this->admin['seller_id'],
            'is_del' => 1,
        ];
        $res = $attachment->getAttachment($where);
        return json($res);
    }

    /**
     * 保存更新的资源
     * @return \think\response\Json
     * @throws \app\exception\ModelException
     * @throws \app\exception\ModelEmptyException
     */
    public function update(Attachment $attachment): \think\response\Json
    {
        if(request()->isPost()){
            $param = input('post.');
            $seller_id = $this->admin['seller_id'];
            try {
                validate(AttachmentValidate::class)->scene('update')->check($param);
            } catch (ValidateException $e) {
                return jsonReturn(-1, $e->getError());
            }
            $where = [
                'id' => $param['id'],
                'seller_id' => $seller_id,
                'is_del' => 1,
            ];
            $res = $attachment -> updateAttachment($where,$param);
            return json($res);
        }
        return jsonReturn(-3,'请求方法错误');
    }

    /**
     * 删除指定资源
     *
     * @throws \app\exception\ModelException
     */
    public function delete(Attachment $attachment): \think\response\Json
    {
        if(request()->isPost()){
            $id = (int)input('id');
            if(!$id){
                return jsonReturn(-1,'文件ID不能为空');
            }
            $where = [
                'id' => $id,
                'seller_id' => $this->admin['seller_id']
            ];
            optEventLog($id,'附件','删除');
            $res = $attachment->softDelAttachment($where);

            return json($res);
        }
        return jsonReturn(-3,'请求方法错误');
    }

    /**
     * @throws \app\exception\ModelException
     * @throws \app\exception\ModelEmptyException
     */
    public function uploadAndSave(Attachment $attachment): \think\response\Json
    {
        if(request()->isPost()){
            $file = request()->file('file');
            $seller_id = $this->admin['seller_id'];
            // 查看文件类型
            $fileName = $file->getOriginalName();
            $fileExt = $file->getOriginalExtension();
            $file_type = fileFormat($fileName);
            $fileType = $this->type[$file_type];

            // 附件大小和类型验证
            // 获取上传配置
            $Settings = new SysSetting();
            $uploadSetting = $Settings->getAllCustomData(['parent_id'=>1,'group'=>'upload','status'=>1],'id desc','id,group,title,value')['data'];
            $uploadSetting = getColumnForKeyArray($uploadSetting,'title');
            $limitSize = $uploadSetting[$file_type.'_size']['value'] * 1024;     // byte
            $fileSize = $file->getSize();       // 单位byte
            if($fileSize > $limitSize){
                return jsonReturn(-1,'文件过大，请修改上传限制或者替换小的文件');
            }
            $extArr = explode(',',$uploadSetting[$file_type.'_ext']['value']);
            if(!in_array($fileExt,$extArr)){
                return jsonReturn(-2,'文件格式错误，请重新上传');
            }
            // 文件信息提取
            $where = [
                'seller_id' => $seller_id,
                'group' => 'upload',
                'title' => 'storage'
            ];
            $place = new SysSetting();
            $type = $place->getSysSetting($where)['data']->toArray()['value'];

            $upload = new Upload();
            $info = $upload->create($file,$seller_id, $type,$file_type);

            if ($info) {
                $uploadInfo = $upload->getUploadFileInfo();
                if ($uploadInfo['code'] == 0) {
                    $uploadInfo['data']['type'] = $fileType;
                    $uploadInfo['data']['size'] = round($fileSize / 1024,2);
                    $res = $attachment->addAttachment($uploadInfo['data']);
                    optEventLog($res['data']['id'],'附件','添加');
                    return json($res);
                } else {
                    return json($uploadInfo);
                }
            }
            return jsonReturn(-1, '上传失败请重新尝试');
        }
        return jsonReturn(-3,'请求方法错误');
    }
}
